﻿<!--@时间：2022-3-7
    @描述：控件-上传临时文件到CENTER_API
    @使用：
        import UploadTemp from "@/components/common/TheUploadTemp.vue"
属性如下：
isDirectoryUpload:是否上传文件夹
onFinished  function - 自定义全部上传完成后的事件，格式onFinished(paths)
onOneFinished function - 自定义上传完一个文件后的事件，格式onOneFinished(cur_index, file_name, webkit_relative_path, response_temp_path)
onFileSeleted function - 当文件选中后触发事件，格式onFileSeleted(files,callback) callback是回调function,由父组件决定是否继续执行下去
onProcessing function - 上传过程，格式onProcessing(cur_per,cancel) cancel是回调function，由父组件决定是否执行取消操作
-->
<template>
  <div>
    <div style="padding:20px 0 20px 0;text-align:left" >
      <el-button icon="el-icon-folder-opened" type="primary" @click="btnChange">点击上传</el-button>
      <input type="file" id="tempFileDir" hidden @change="fileChange" webkitdirectory v-if="isDirectoryUpload">
      <input type="file" id="tempFile" hidden multiple @change="fileChange" v-else>
    </div>
    <div style="padding:20px 0 20px 0;text-align:left" >
      <label>{{tips}}</label>
    </div>
    <el-table :data = "fileList" stripe max-height="500">
      <el-table-column fixed align="center" label="路径" prop="file_path" min-width="40%"></el-table-column>
      <el-table-column align="center" label="进度">
        <template slot-scope = "scope">
        <el-progress :percentage="scope.row.percentage" :color="scope.row.mcolor"></el-progress>
        </template>
      </el-table-column>
      <el-table-column align="center" label="信息提示" prop="msg"></el-table-column>
    </el-table>
  </div>
</template>

<script>
import axios from 'axios'
export default {
  props: ['isDirectoryUpload'],
  data () {
    return {
      fileList: [{
        file_path: '',
        percentage: 0,
        mcolor: '#409eff',
        msg: ''
      }],
      paths: [],
      cancelSource: null,
      tips: ''
    }
  },
  mounted () {
    this.initPage()
  },
  methods: {
    // 初始化页面时
    initPage () {
      console.debug('init')
      this.fileList = []
      this.paths = []
      this.tips = ''
    },
    btnChange () {
      if (this.isDirectoryUpload) {
        let file = document.getElementById('tempFileDir')
        file.value = ''
        file.click()
      } else {
        let file = document.getElementById('tempFile')
        file.value = ''
        file.click()
      }
    },
    // 上传文件
    fileChange (e) {
      try {
        let fu = this.isDirectoryUpload ? document.getElementById('tempFileDir') : document.getElementById('tempFile')
        if (fu == null) return
        this.fileList = []
        if (fu.files.length > 1000) {
          this.$message({
            message: '操作失败-上传文件数不可超过1000',
            type: 'error',
            duration: 3000
          })
          return
        }
        this.tips = '已选择' + fu.files.length + '个文件'
        this.$emit('onFileSeleted', fu.files, () => {
          for (let i = 0; i < fu.files.length; i++) {
            let tableitem = {
              file_path: fu.files[i].webkitRelativePath ? fu.files[i].webkitRelativePath : fu.files[i].name,
              percentage: 0,
              mcolor: '#409eff',
              msg: '',
              file: fu.files[i]
            }
            this.fileList.push(tableitem)
          }
          this.sendFileInfo(0)
        })
      } catch (error) {
        console.debug('choice dir err:', error)
        this.$message({
          message: '操作失败',
          type: 'error',
          duration: 3000
        })
      }
    },
    sendFileInfo (index) {
      if (index >= this.fileList.length) return
      let self = this
      let formData = new FormData()
      formData.append('file', self.fileList[index].file)
      self.cancelSource = axios.CancelToken.source()
      axios({
        url: $URL.CENTER_API + '/md_form/upload/temp',
        method: 'post',
        headers: {
          'Content-Type': 'multipart/form-data;boundary = ' + new Date().getTime()
        },
        data: formData,
        cancelToken: self.cancelSource.token,
        onUploadProgress: ProgressEvent => {
          if (ProgressEvent.lengthComputable) {
            let currentPer = parseInt(ProgressEvent.loaded / ProgressEvent.total * 10000) / 100
            self.fileList[index].percentage = currentPer > 100 ? 100 : currentPer
            self.$emit('onProcessing', self.fileList[index].percentage, self.cancelSource)
          }
        }
      }).then(data => {
        let dataResult = data.data.result
        if (dataResult.code === 'success') {
          self.fileList[index].percentage = 100
          self.fileList[index].msg = '上传成功'
          self.paths.push(dataResult.data.temp_path)
          self.tips = '当前进度:' + (index + 1) + '/' + self.fileList.length
          self.$emit('onOneFinished', index, self.fileList[index].file.name, self.fileList[index].file.webkitRelativePath, dataResult.data.temp_path)
        } else {
          self.fileList[index].msg = dataResult.msg
        }
        if (index === (self.fileList.length - 1)) {
          self.$emit('onFinished', self.paths)
        }
        self.sendFileInfo(index + 1)
      }).catch(error => {
        self.fileList[index].msg = error
        self.sendFileInfo(index + 1)
      })
    }
  },
  watch: {
  }
}
</script>
